//
//  KSPickerPhotoAlbumViewController.swift
//  Supermarket
//
//  Created by Black_Crystal on 2017/9/19.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import Photos

protocol PickerPhotoCompleteDelegate: NSObjectProtocol {
    func pickerPhotoComplete(asset: [PHAsset])
}

//相簿列表项
struct ImageAlbumItem {
    //相簿名称
    var title:String?
    //相簿内的资源
    var fetchResult:PHFetchResult<PHAsset>
}

class KSPickerPhotoAlbumViewController: KSBaseViewController,PickerPhotoDelegate {
    weak var delegate: PickerPhotoCompleteDelegate?
    var tableview: UITableView!
    //相簿列表项集合
    var items:[ImageAlbumItem] = []
    //每次最多可选择的照片数量
    var maxSelected:Int = Int.max
    var cameraChooseNumber: Int = Int.max
    var selectPhotoArray: [PHAsset] = []
    var tempPhotoArray: [PHAsset] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rightBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 64))
        rightBtn.setTitle("取消", for: .normal)
        rightBtn.setTitleColor(UIColor.blue, for: .normal)
        rightBtn.addTarget(self, action: #selector(cancel), for: .touchDown)
        let rightBarItem = UIBarButtonItem.init(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightBarItem
        
        self.tableview = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight))
        tableview.register(KSPickerPhotoAlbumTableViewCell.self, forCellReuseIdentifier: "KSPickerPhotoAlbumTableViewCell")
        tableview.delegate = self
        tableview.dataSource = self
        tableview.rowHeight = 50
        self.view.addSubview(tableview)
            
            //申请权限
            PHPhotoLibrary.requestAuthorization({ (status) in
                if status != .authorized {
                    return
                }
                
                // 列出所有系统的智能相册
                let smartOptions = PHFetchOptions()
                let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum,
                                                                          subtype: .albumRegular,
                                                                          options: smartOptions)
                self.convertCollection(collection: smartAlbums)
                
                //列出所有用户创建的相册
                let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil)
                self.convertCollection(collection: userCollections
                    as! PHFetchResult<PHAssetCollection>)
                
                //相册按包含的照片数量排序（降序）
                self.items.sort { (item1, item2) -> Bool in
                    return item1.fetchResult.count > item2.fetchResult.count
                }
                
                //异步加载表格数据,需要在主线程中调用reloadData() 方法
                DispatchQueue.main.async{
                    //首次进来后直接进入第一个相册图片展示页面（相机胶卷）
                    let imageCollectionVC = KSPickerPhotoViewController()
                        imageCollectionVC.title = self.items.first?.title
                        imageCollectionVC.assetsFetchResults = self.items.first?.fetchResult
                        imageCollectionVC.tempSelect = self.selectPhotoArray
                        imageCollectionVC.selectPhotoResults = self.selectPhotoArray
                        imageCollectionVC.maxSelected = self.maxSelected
                    imageCollectionVC.cameraChooseNumber = self.cameraChooseNumber
                        imageCollectionVC.delegate = self
                    self.navigationController?.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(imageCollectionVC,
                                                                      animated: false)
                    
                    self.tableview?.reloadData()
                }
            })
    }
    
    @objc func cancel() {
        //退出当前视图控制器
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    //转化处理获取到的相簿
    private func convertCollection(collection:PHFetchResult<PHAssetCollection>){
        for i in 0..<collection.count{
            //获取出但前相簿内的图片
            let resultsOptions = PHFetchOptions()
            resultsOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                               ascending: false)]
            resultsOptions.predicate = NSPredicate(format: "mediaType = %d",
                                                   PHAssetMediaType.image.rawValue)
            let c = collection[i]
            let assetsFetchResult = PHAsset.fetchAssets(in: c , options: resultsOptions)
            //没有图片的空相簿不显示
            if assetsFetchResult.count > 0 {
                let title = titleOfAlbumForChinse(title: c.localizedTitle)
                items.append(ImageAlbumItem(title: title,
                                              fetchResult: assetsFetchResult))
            }
        }
    }
    
    //由于系统返回的相册集名称为英文，我们需要转换为中文
    private func titleOfAlbumForChinse(title:String?) -> String? {
        if title == "Slo-mo" {
            return "慢动作"
        } else if title == "Recently Added" {
            return "最近添加"
        } else if title == "Favorites" {
            return "个人收藏"
        } else if title == "Recently Deleted" {
            return "最近删除"
        } else if title == "Videos" {
            return "视频"
        } else if title == "All Photos" {
            return "所有照片"
        } else if title == "Selfies" {
            return "自拍"
        } else if title == "Screenshots" {
            return "屏幕快照"
        } else if title == "Camera Roll" {
            return "相机胶卷"
        }
        return title
    }
    
    func pickerTempPhoto(asset: [PHAsset]) {
        self.tempPhotoArray = asset
    }
    
    func pickerPhoto(asset: [PHAsset]) {
        self.selectPhotoArray = asset
        self.delegate?.pickerPhotoComplete(asset: asset)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension KSPickerPhotoAlbumViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSPickerPhotoAlbumTableViewCell", for: indexPath) as! KSPickerPhotoAlbumTableViewCell
        let item = self.items[indexPath.row]
        cell.titleLabel.text = "\(item.title ?? "")"
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let imageCollectionVC = KSPickerPhotoViewController()
        imageCollectionVC.title = self.items[indexPath.row].title
        imageCollectionVC.assetsFetchResults = self.items[indexPath.row].fetchResult
        imageCollectionVC.maxSelected = self.maxSelected
        imageCollectionVC.cameraChooseNumber = self.cameraChooseNumber
        imageCollectionVC.tempSelect = self.tempPhotoArray
        imageCollectionVC.delegate = self
        self.navigationController?.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(imageCollectionVC,
                                                      animated: false)
    }
}




